<template>
  <div>
    <div>
      <uNavbar>
        <nut-input @clear="search()" show-clear-icon :clearable="true" v-model="keyword" @confirm="search"
          :input-style="searchStyle" :custom-style="searchStyle" :border="false" placeholder="请输入搜索商品">
          <template #left>
            <div pl-18rpx flex flex-a-c> <nut-icon name="search" /> </div>
          </template>
        </nut-input>

        <div w-100rpx text-center @click="goodsViewType === 'one' ? goodsViewType = 'two' : goodsViewType = 'one'">
          <nut-icon name="category" v-if="goodsViewType !== 'two'"></nut-icon>
          <nut-icon name="horizontal" v-if="goodsViewType !== 'one'"></nut-icon>
        </div>
      </uNavbar>
      <div class="navbar" flex flex-a-c>
        <div @click="changeMenu(item)" h-45px flex flex-a-c flex-col flex-j-c position-relative
          :class="{ 'text-main-color': menuCurrent === item.value, 'active': menuCurrent === item.value }"
          v-for="(item, index) in menu" :key="index">
          <div flex flex-a-c>
            <div>
              {{ item.label }}
            </div>

            <nut-config-provider v-if="item.value === 'buyCount' || item.value === 'price'" :theme-vars="{
          iconWidth: '12px',
          iconHeight: '12rpx',
          iconLineHeight: '10px'
        }">
              <div flex flex-col>
                <nut-icon :custom-color="item.sort === 'asc' ? colors.themeColor : '#999'" h-10rpx size="8"
                  name="triangle-up"></nut-icon>
                <nut-icon :custom-color="item.sort === 'desc' ? colors.themeColor : '#999'" h-10rpx size="8"
                  name="triangle-down"></nut-icon>
              </div>
            </nut-config-provider>
          </div>
          <div h-3rpx w-50rpx bottom-0 absolute bg-main-color rounded-10rpx v-if="menuCurrent === item.value"></div>
        </div>
      </div>
    </div>
    <div p-16rpx>
      <scroll-view :scroll-top="scrollTop" @scrolltolower="reachBottom" :lower-threshold="100" scroll-with-animation
        :style="{ height: scrollHeight() }" :scroll-y="true">
        <div v-if="isShow">
          <div v-if="goodsList.records.length">
            <div v-if="goodsViewType === 'one'" :key="index" v-for="(item, index) in goodsList.records" mb-20rpx>
              <oneRow :res="item"></oneRow>
            </div>
            <div flex flex-wrap v-if="goodsViewType === 'two'">
              <div :style="'width: 50%'" :key="index" v-for="(item, index) in goodsList.records">
                <twoRow :res="item"></twoRow>
              </div>
            </div>
          </div>
          <empty v-if="!goodsList.records.length" />
        </div>
      </scroll-view>
    </div>
    <nut-popup position="right" round :custom-style="{ width: '80%', height: '100vh' }" v-model:visible="showSort">
      <div relative overflow-auto p-32rpx>
        <scroll-view scroll-y scroll-with-animation :style="{ height: popupHeight('height'), marginTop: popupHeight('marginTop') }">
          <div>
            <div mb-40rpx font-bold text-28rpx>品牌</div>
            <div flex flex-a-c flex-wrap gap-20rpx v-if="sortData.brands">
              <div :class="brand.__selected ? ['text-main-color', 'bg-main-color-10'] : 'bg-warmGray-100'" py-16rpx
                px-24rpx text-24rpx rounded-10rpx flex flex-a-c @click="handleSort(brand, brandsIndex, 'brand')"
                :key="brandsIndex" v-for="(brand, brandsIndex) in sortData.brands">
                {{ brand.name }}
              </div>
            </div>
          </div>
          <div my-40rpx font-bold text-28rpx>全部分类</div>
          <div flex flex-a-c flex-wrap gap-20rpx v-if="sortData.categories">
            <div :class="categoryId.__selected ? ['text-main-color', 'bg-main-color-10'] : 'bg-warmGray-100'" py-16rpx
              px-24rpx text-24rpx rounded-10rpx flex flex-a-c :key="categoriesIndex"
              v-for="(categoryId, categoriesIndex) in sortData.categories"
              @click="handleSort(categoryId, categoriesIndex, 'categoryId')">
              {{ categoryId.name }}
            </div>
          </div>
          <div>
            <div my-40rpx font-bold text-28rpx>价格区间</div>
            <div flex flex-a-c>
              <nut-input v-model="minPrice" :border="false" :input-style="InputStyle" type="number" placeholder="最低价" />
              <div>-</div>
              <nut-input v-model="maxPrice" :border="false" :input-style="InputStyle" type="number" placeholder="最高价" />
            </div>
          </div>
          <div v-if="sortData.paramOptions">
            <div v-for="(param, paramIndex) in sortData.paramOptions" :key="paramIndex">
              <div my-40rpx font-bold text-28rpx>{{ param.key }}</div>
              <div flex flex-a-c flex-wrap gap-20rpx v-if="param.values">
                <div :class="value.__selected ? ['text-main-color', 'bg-main-color-10'] : 'bg-warmGray-100'" py-16rpx
                  px-24rpx text-24rpx rounded-10rpx flex flex-a-c font-0 v-for="(value, i) in param.values"
                  @click="handleSort(value, i, 'prop', param)">
                  {{ value.title }}
                </div>
              </div>
            </div>

          </div>
        </scroll-view>
        <div w-full>
          <div h-100rpx px-32rpx flex flex-a-c flex-j-c gap-20rpx>
            <nut-button flex-1 @click="resetSlot" type="default">重置</nut-button>
            <nut-button flex-1 @click="confirmSlot" type="primary">确定</nut-button>
          </div>
        </div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup lang="ts">
import { getGoodsList, getGoodsRelated } from '@/api/goods';
import empty from '@/components/empty/index.vue';
import oneRow from '@/components/goods-list/1row.vue';
import twoRow from '@/components/goods-list/2row.vue';
import { searchStyle } from '@/components/goods-list/common';
import uNavbar from '@/components/navbar/index.vue';
import { InputStyle, colors } from '@/constants/injection-key';

const props = defineProps<{
  keyword: any,
  router: any
}>()

const scrollTop = ref<number>(0) //scroll 为0 回到顶部
const showSort = ref<boolean>(false) //展示筛选内容
const isShow = ref<boolean>(false) //是否展示内容
const selectedWay = ref<any>({
  brand: [],
  categoryId: [],
  prop: []
})

const sortData = ref<any>("")
const minPrice = ref<any>('')
const maxPrice = ref<any>('')
const searchForm = ref<any>({
  pageSize: 10,
  pageNumber: 1
})


const sortParams = ref<any>({
  // price: "", //价格,示例值(10_30)
  // prop: "", //属性:参数名_参数值@参数名_参数值,示例值(屏幕类型_LED@屏幕尺寸_15英寸)
  // brandId:"", //品牌,可以多选 品牌Id@品牌Id@品牌Id
  categoryId: ''
})
const goodsList = ref<any>({
  records: [],
  total: 0
})
const menuCurrent = ref<string>("normal")
const menu = ref<any>([
  {
    label: "综合排序",
    value: "normal"
  },
  {
    label: "销量",
    value: "buyCount",
    sort: ""
  },
  {
    label: "价格",
    value: "price",
    sort: ""
  },
  {
    label: "筛选",
    value: "screen"
  },
])
const goodsViewType = ref<string>('two') // two 一行两个 one 一行一个
const keyword = ref<string>('')

const scrollHeight = () => {
  // #ifdef H5
  return 'calc(100vh - (180rpx + 32rpx))'
  // #endif
}

// 兼容popupHeight
const popupHeight = (type: 'height' | 'marginTop') => {

  // #ifndef H5
  return type === 'marginTop' ? '180rpx' : 'calc(100vh - (280rpx + 32rpx + 100rpx))'
  // #endif
}

watch(() => goodsViewType.value, async () => {
  scrollTop.value = 0
})
watch(() => props.keyword, async (val) => {
  if (val) {
    keyword.value = val;
    search();
  }
}, { immediate: true, deep: true })


// 点击筛选的内容
function resetSlot() {
  sortParams.value = {
    categoryId: props.router.categoryId || ''
  };
  searchForm.value = {
    pageSize: 10,
    pageNumber: 1
  };
  showSort.value = false;

  minPrice.value = '';
  maxPrice.value = '';
  goodsList.value.records = [];
  changeMenu({
    value: 'normal'
  })



}
//
function confirmSlot() {
  // 处理品牌（多选
  if (!sortParams.value.brandId) {
    sortParams.value.brandId = [];
  } else {
    sortParams.value.brandId = [sortParams.value.brandId];
  }

  // 如果选中品牌 赋值
  selectedWay.value['brand'].forEach((item: any) => {
    if (item.__selected) {
      sortParams.value.brandId.push(item.value);
    }
  });

  sortParams.value.brandId = sortParams.value.brandId.join('@') || '';

  // 处理分类 (单选)
  if (selectedWay.value['categoryId'][0]) {
    sortParams.value.categoryId = selectedWay.value['categoryId'][0].value;
  }
  if (!sortParams.value.prop) {
    sortParams.value.prop = [];
  } else {
    sortParams.value.prop = [sortParams.value.prop];
  }

  selectedWay.value['prop'].forEach((item: any) => {
    if (item.__selected) {
      sortParams.value.prop.push(`${item.parent}_${item.title}`);
    }
  });
  sortParams.value.prop = sortParams.value.prop.join('@');
  // 处理价格
  if (minPrice.value || maxPrice.value) {
    sortParams.value.price = `${minPrice.value}_${maxPrice.value}`;
  } else {
    sortParams.value.price = 0;
  }

  goodsList.value.records = [];

  searchForm.value.pageNumber = 1;
  searchForm.value = {
    ...searchForm.value,
    ...sortParams.value
  }
  fetchRelated()
  fetch();
  showSort.value = false;
}

// 点击筛选的内容
function handleSort(val: any, index: number, type: any, parent?: any) {
  if (type === 'prop') {
    val.parent = parent.key;
    if (sortParams.value.prop) {
      sortParams.value.prop = sortParams.value.prop.replace(val.parent + "_" + val.title, "");
    }
  }
  selectedWay.value[type].push(val);
  if (type === 'categoryId') {
    sortData.value.categories.forEach((item: any) => {
      item.__selected = false;
    });
    val.__selected = true;
  } else {
    val.__selected = !val.__selected;
    if (type === 'brand') {
      if (sortParams.value.brandId) {
        sortParams.value.brandId = sortParams.value.brandId.replace(val.value, "");
      }
    }
  }
}

// 切换菜单
function changeMenu(val: any) {
  menuCurrent.value = val.value
  if (val.value === 'price' || val.value === 'buyCount') {
    // 如果是价格或者销量，先将排序字段置空
    val.value === 'price' ? menu.value.find((item: any) => item.value === 'buyCount').sort = '' : ''
    val.value === 'buyCount' ? menu.value.find((item: any) => item.value === 'price').sort = '' : ''
    val.sort = val.sort === 'desc' ? 'asc' : 'desc'
    searchForm.value.order = val.sort
    searchForm.value.sort = val.value
  }
  else {
    delete searchForm.value.order
    delete searchForm.value.sort
    menu.value = menu.value.map((item: any) => {
      if (item.sort) {
        item.sort = ""
      }
      return item
    })
  }
  if (val.value === 'screen') {
    showSort.value = true
  } else {
    // init()
  }

}

// 触底加载
function reachBottom() {
  if (searchForm.value.pageSize * searchForm.value.pageNumber < goodsList.value.total) {
    searchForm.value.pageNumber++
    fetch()
  }
}

function init() {
  isShow.value = false
  goodsList.value.records = []
  searchForm.value.pageSize = 10
  searchForm.value.pageNumber = 1
  fetch()
  fetchRelated();
}

async function fetch() {
  const res = await getGoodsList(searchForm.value)
  isShow.value = true
  if (res.data.success) {
    goodsList.value.records.push(...res.data.result.records)
    goodsList.value.total = res.data.result.total
  }
}

async function fetchRelated() {
  const params = {
    keyword: sortParams.value.keyword
  }
  const res = await getGoodsRelated(params)
  if (res.data.success) {
    for (let item of Object.keys(res.data.result)) {

      res.data.result[item].forEach((child: any) => {
        child.__selected = false;
        if (item === 'brands' && sortParams.value.brandId) {
          child.__selected = sortParams.value.brandId.indexOf(child.value) > -1;
        }
        if (item === 'categories' && sortParams.value.categoryId) {
          child.__selected = sortParams.value.categoryId === child.value;
        }

        // 循环出和品牌分类一样的数据格式
        if (child.values) {
          child.values = child.values.map((item: any) => ({
            title: item,
            __selected: sortParams.value.prop ? sortParams.value.prop.indexOf(`${child.key}_${item}`) > -1 : false
          }));
        }
      });
    }
    sortData.value = res.data.result;
  }
}

function search() {
  goodsList.value.records = []
  searchForm.value.keyword = keyword.value
  sortParams.value.keyword = keyword.value

  changeMenu({
    value: 'normal'
  })
}


onMounted(() => {
  console.log("props.router", props.router)
  if (props.router.category) {
    searchForm.value.categoryId = props.router.category
  }
  if (props.router.promotionType) {
    searchForm.value.promotionType = props.router.promotionType;
  }
  if (props.router.promotionsId) {
    searchForm.value.promotionsId = props.router.promotionsId;
  }
  init()
})
</script>


<style scoped lang="scss">
.navbar {
  width: 100%;
  border-bottom: 1px solid #ededed;
  height: 45px;
  background-color: #fff;
  justify-content: space-around;

}

.active {
  font-weight: bold;

}
</style>
